<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>添加与移除marker</title>
</head>
<script charset="utf-8"
    src="https://map.qq.com/api/gljs?v=1.exp&key=MZQBZ-EKRKU-SK5VS-2DA2P-GIL6V-BUBEL"></script>
<style type="text/css">
    html,
    body {
        height: 100%;
        margin: 0px;
        padding: 0px;
    }

    #container {
        width: 100%;
        height: 100%;
    }

    #removeMarker{
        position: absolute;
        left: 30px;
        top: 50px;
        z-index: 9999;
    }

      #info{
        position: absolute;
        left: 20px;
        top: 20px;
        font-size: 14px;
        background: #FFF;
        width: 270px;
        padding: 10px;
        border-radius: 3px;
    }
</style>

<body onload="initMap()">
    <div id="container"></div>
    <div id="info">当前点击坐标为：<span id="position"></span></div>
    <input type="button" id="removeMarker" onclick="removeMarker()" value="removeMarker">
    <script>
        var map;
        var longitude;
        var latitude;
        var markerLayer;

        //初始化地图
        function initMap() {
            var position = document.getElementById("position");

            var center = new TMap.LatLng(39.984104, 116.307503);//设置中心点坐标
            //初始化地图
            map = new TMap.Map("container", {
                center: center
            });
            
            //绑定点击事件
            map.on("click",function(evt){
                latitude = evt.latLng.getLat().toFixed(6);
                longitude = evt.latLng.getLng().toFixed(6);
                position.innerHTML = latitude + "," + longitude;
            })

            markerLayer = new TMap.MultiMarker({
                    id: 'marker-layer',
                    map: map
            });


            //监听点击事件添加marker
            map.on("click", (evt) => {
                if (markerLayer == null){
                    markerLayer = new TMap.MultiMarker({
                        id: 'marker-layer',
                        map: map
                    });
                }
                markerLayer.add({
                    position: evt.latLng
                });  
                                    
            });
        };
      
        //移除marker事件
        function removeMarker() {
            if(markerLayer != null){
                 markerLayer.setMap(null)
                 markerLayer = null;
            }
        }

    </script>
</body>

</html>